import Cfg from './config.js';
import Cry from './crypto.js';
import Msg from './message.js';
import Nav from './navigation.js';

const _post = (url,data,success,hook,fail) =>{
	_http('POST',url,data,success,hook,fail);
}

const _get = (url,data,success,hook,fail) =>{
	_http('GET',url,data,success,hook,fail);
}

const _setLang=(code)=>{	
	uni.setStorageSync('_LANGUAGE_',code);	
}

const _getLang = ()=>{
	return uni.getStorageSync('_LANGUAGE_') || 'zh-CN';
}

const _setToken = (token)=>{
	uni.setStorageSync('_TOKEN_',token);
}

const _getToken = () =>{
	return uni.getStorageSync('_TOKEN_') || '';
}

const _delToken = () =>{
	uni.removeStorageSync('_TOKEN_');
}

//网络请求
const _http = (type,url,data,success,hook,fail,num=1)=>{
	let token = _getToken();
	let lang = _getLang();		
	data = Object.assign({token:token,platform:'APP',lang:lang}, data); 
		//console.log(num)
	
		uni.showLoading()
	uni.request({
		url:Cfg.Setting.root+url,
		data:data,		
		dataType:"json",
		method:type,		
		header:{'content-type':'application/x-www-form-urlencoded'},
		success(res){	
			uni.hideLoading();
			if (res.statusCode !== 200) { 				
				Msg.Fail('网络请求出错:'+url)
				return false;          
			}	
			let data = null;	 
			if(Cfg.Setting.encrypt){//加密
				data = Cry.secret(res.data,true);
				data = JSON.parse(data);
			}else{
				data = res.data;
				if(typeof data!=='object'){				 
					Msg.Fail('网络请求出错:'+url)
					return false;    
				}				 
			}			
			if(hook){
				success && success(data);
				return false;
			}		 
			if(data.code == -10){				
				Msg.Fail(data.msg,()=>{					
					Nav._to({url:Cfg.Setting.login_route,type:1});
				}); 
				return false;
			}
			
			if (data.code === 0) {
				Msg.Fail(data.msg);
				return false;			  
			}else{
				success && success(data);
			}       			  
		},
		fail(res){
			// if(num<4){
			// 	_http(type,url,data,success,hook,fail,num+1);
			// }
			
			// if(hook){
			// 	fail && fail(res.errMsg);
			// }else{
			// 	Msg.Fail(res.errMsg);
			// 	fail && fail(res);
			// }
		},
		complete(res){
			//complete && complete(res);			
		} 
	})	
}

module.exports = {    
	_get,
	_post,
	_setToken,
	_getToken,
	_delToken,
	_setLang,
	_getLang
}